package com.insight.entity;

import jakarta.persistence.*;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Size;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.hibernate.annotations.CreationTimestamp;
import org.hibernate.annotations.UpdateTimestamp;

import java.time.LocalDateTime;

/**
 * T050: 索引元数据实体类
 * 记录数据库表索引的元数据信息
 *
 * @author Insight Team
 */
@Entity
@Table(name = "metadata_index",
        indexes = {
                @Index(name = "idx_metadata_index_table", columnList = "table_id"),
                @Index(name = "idx_metadata_index_name", columnList = "index_name"),
                @Index(name = "idx_metadata_index_type", columnList = "index_type")
        })
@Data
@NoArgsConstructor
@AllArgsConstructor
public class MetadataIndex {

    /**
     * 主键ID
     */
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    /**
     * 关联的表
     */
    @NotNull(message = "所属表不能为空")
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "table_id", nullable = false)
    private MetadataTable table;

    /**
     * 索引名称
     */
    @NotNull(message = "索引名称不能为空")
    @Size(max = 200, message = "索引名称长度不能超过200")
    @Column(name = "index_name", nullable = false, length = 200)
    private String indexName;

    /**
     * 索引类型 (PRIMARY, UNIQUE, NORMAL, FULLTEXT等)
     */
    @Size(max = 50, message = "索引类型长度不能超过50")
    @Column(name = "index_type", length = 50)
    private String indexType;

    /**
     * 索引包含的列名列表(逗号分隔)
     */
    @Column(name = "column_names", length = 1000)
    private String columnNames;

    /**
     * 是否唯一索引
     */
    @Column(name = "is_unique")
    private Boolean isUnique;

    /**
     * 索引注释
     */
    @Column(name = "index_comment", length = 1000)
    private String indexComment;

    /**
     * 元数据记录创建时间
     */
    @CreationTimestamp
    @Column(name = "created_at", nullable = false, updatable = false)
    private LocalDateTime createdAt;

    /**
     * 元数据记录更新时间
     */
    @UpdateTimestamp
    @Column(name = "updated_at", nullable = false)
    private LocalDateTime updatedAt;

    /**
     * 生命周期回调: 持久化之前
     * 设置默认值,避免null
     */
    @PrePersist
    public void prePersist() {
        if (this.indexType == null) {
            this.indexType = "NORMAL";
        }
        if (this.isUnique == null) {
            this.isUnique = false;
        }
    }
}
